<template>
<div>
    {{progress}}
    <div id="editor" style="height: 100px"></div>
</div>
</template>

<script>
import E from "wangeditor";
import Config from '@/config'
var OSS = require('ali-oss');
import { getUUID } from "@/libs";

export default {
    data() {
        return {
            clinet: null,
            editor: null,
            loading: false,
            progress: 0,
            content: null
        }
    },

    mounted() {
        this.$nextTick(function() {
            this.initEditor()
        });
    },

    methods: {
        async initEditor() {
            const _this = this
            // 初始化阿里云OSS
            this.clinet = new OSS(Config.Aliyun.oss);

            const editor = new E('#editor')
            editor.config.showFullScreen = false
            editor.config.zIndex = 1
            editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
            editor.config.uploadVideoAccept = ['mp4']

            // 配置 onchange 回调函数，将数据同步到 vue 中
            editor.config.onchange = (newHtml) => {
                _this.content = newHtml
            }
            // 自定义上传图片
            editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
                _this.loading = _this.$loading({ lock: true, text: '上传中，请稍等', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });

                await _this.handleUpload(resultFiles, insertImgFn)

                _this.loading.close()
            }
            // 自定义上传视频
            editor.config.customUploadVideo = async function (resultFiles, insertVideoFn) {
                _this.loading = _this.$loading({ lock: true, text: '上传中，请稍等', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });

                await _this.handleUpload(resultFiles, insertVideoFn)

                _this.loading.close()
            }
            editor.create()
            this.editor = editor
        },
        /**
         * 上传到阿里云OSS
         */
        async handleUpload(resultFiles, insert) {
            const _this = this
            for(const file of resultFiles) {
                try {
                    let result = await this.clinet.multipartUpload(getUUID(), file, {
                        progress(p, checkpoint) {
                            // console.log('Object的上传进度', p);
                            // console.log('分片上传的断点信息', checkpoint);
                            _this.progress = p
                        }
                    })
                    console.log(result);
                    const url = result.res.requestUrls[0].split('?')[0]
                    insert(url)
                } catch(err) {
                    _this.loadingInstance.close()
                    console.log(err);
                }
            }
        }

    },
    beforeDestroy() {
        // 调用销毁 API 对当前编辑器实例进行销毁
        this.editor.destroy()
        this.editor = null
    }

};
</script>

<style lang="scss" scoped></style>
